package com.spring.controller;

import com.spring.entity.Company;
import com.spring.entity.Position;
import com.spring.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class PositionController {
    @Autowired
    private PositionService positionService;

    @RequestMapping("findPosition.action")
    @ResponseBody
    public List<Position> findPosition(String pname, Double minSal, Double maxSal){
        return this.positionService.find(pname,minSal,maxSal);
    }

    @RequestMapping("deletePosition.action")
    public void deletePosition(int pid, HttpServletResponse resp) throws IOException {
        try {
            this.positionService.remove(pid);
            resp.getWriter().print("ok");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().print("error");

        }
    }

    @RequestMapping("findAllComp.action")
    @ResponseBody
    public List<Company> findAllComp(String pname, Double minSal, Double maxSal){
        return this.positionService.findAllComp();
    }

    @RequestMapping("addPosition.action")
    public ModelAndView addPosition(Position position){
        ModelAndView modelAndView = new ModelAndView();
        try {
            this.positionService.add(position);
            modelAndView.setViewName("redirect:/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("error","添加失败");
            modelAndView.setViewName("/positionAdd.jsp");
        }
        return modelAndView;
    }

    @RequestMapping("findPositionById.action")
    public String findPositionById(Integer pid, Model model){
        Position postion = this.positionService.findById(pid);
        model.addAttribute("position",postion);
        return "forward:/positionUpdate.jsp";
    }

    @RequestMapping("updatePosition.action")
    public ModelAndView updatePosition(Position position){
        ModelAndView modelAndView = new ModelAndView();
        try {
            this.positionService.replace(position);
            modelAndView.setViewName("redirect:/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("error","修改失败");
            modelAndView.setViewName("/positionUpdate.jsp");
        }
        return modelAndView;
    }


}
